package io.gps.datatransfer.utils;

import org.apache.mina.core.buffer.IoBuffer;

/**
 * 上行指令封包
 * @author gps
 *
 */
public class UpMessage {

	public static IoBuffer getMessage(IoBuffer data) throws Exception{
		IoBuffer buf = IoBuffer.allocate(15);
		buf.setAutoExpand(true);
		byte b;
		while(data.hasRemaining()){
			b = data.get();
			if(b==0x7d && data.hasRemaining()){
				b = data.get();
				if(b==0x02){
					buf.put((byte)0x7e);
					continue;
				}else if(b==0x01){
					buf.put((byte)0x7d);
					continue;
				}else{
					throw new Exception("非法信息");
				}
			}
			buf.put(b);
		}
		buf.shrink();  //释放无用资源
		buf.flip();
		int lmt = buf.limit();
		buf.position(0);
		int pc = ByteUtils.check(buf,lmt-1);

		int checkCode=buf.getUnsigned();
		if(pc!=checkCode){
			throw new Exception("验证码错误");
		}
		buf.position(0);
		int messageID = buf.getUnsignedShort();
		//得到消息属性部分原始数据
		int mlen=buf.getUnsignedShort();

		int msgLen =  mlen&0x3FF;//获得数据长度
		StringBuilder telphone = new StringBuilder();
		for(int i = 4;i<10;i++){
			telphone.append(ByteUtils.decodeBCD(buf.getUnsigned()));
		}
		if(msgLen==buf.remaining()-1){
			buf.limit(buf.position()+msgLen);
			return buf.compact().flip();
			
		}else{
			throw new Exception("数据长度错误:"+msgLen+"!="+(buf.remaining()-1));
		}
	}

	
}
